<template>
  <div class="data-item-manager">
    <div class="header-actions">
      <el-button type="primary" @click="openAddDialog">
        <el-icon><Plus /></el-icon> 新增数据项
      </el-button>
      <el-button type="success" @click="importDataItems">
        <el-icon><Upload /></el-icon> 导入数据项
      </el-button>
      <el-button type="info" @click="exportDataItems">
        <el-icon><Download /></el-icon> 导出数据项
      </el-button>
    </div>

    <!-- 数据项列表 -->
    <el-table
      :data="paginatedDataItems"
      v-loading="loading"
      border
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column prop="name" label="名称" width="150" />
      <el-table-column prop="unit" label="单位" width="100" />
      <el-table-column prop="display_mode" label="显示方式" width="120" />
      <el-table-column label="图标" width="80">
        <template #default="scope">
          <el-icon>
            <component :is="scope.row.icon" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column label="颜色" width="80">
        <template #default="scope">
          <div class="color-preview" :style="{ backgroundColor: scope.row.color }"></div>
        </template>
      </el-table-column>
      <el-table-column prop="mapping_name" label="映射名" width="180" />
      <el-table-column label="测试值" width="180">
        <template #default="scope">
          <div class="test-value">
            <span v-if="scope.row.testValue !== undefined">{{ scope.row.testValue }}</span>
            <span v-else>-</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="250">
        <template #default="scope">
          <el-button link type="primary" @click="openEditDialog(scope.row)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button link type="danger" @click="confirmDelete(scope.row)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
          <el-button link type="success" @click="testDataItem(scope.row)" :loading="scope.row.testing">
            <el-icon><Monitor /></el-icon> 测试
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑数据项' : '新增数据项'"
      width="500px"
    >
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入数据项名称" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位，如kg、m等" />
        </el-form-item>
        <el-form-item label="显示方式" prop="display_mode">
          <el-select v-model="form.display_mode" placeholder="请选择显示方式" style="width: 100%">
            <el-option label="数值" value="number" />
            <el-option label="文本" value="text" />
            <el-option label="状态" value="status" />
          </el-select>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select v-model="form.icon" placeholder="请选择图标" style="width: 100%">
            <el-option
              v-for="icon in availableIcons"
              :key="icon.name"
              :label="icon.name"
              :value="icon.name"
            >
              <div style="display: flex; align-items: center;">
                <el-icon>
                  <component :is="icon.name" />
                </el-icon>
                <span style="margin-left: 8px;">{{ icon.name }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="form.color" show-alpha />
        </el-form-item>
        <el-form-item label="映射名" prop="mapping_name">
          <el-input v-model="form.mapping_name" placeholder="请输入映射名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="300px"
    >
      <div>确定要删除数据项 "{{ currentItem?.name }}" 吗？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteItem" :loading="deleting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useDeviceStore } from '@/stores/deviceStore'
import { useAuthStore } from '@/store/authStore'
import {
  Edit,
  Delete,
  Plus,
  Monitor,
  Connection,
  DataLine,
  Setting,
  Timer,
  Odometer,
  TrendCharts,
  Box,
  Loading,
  Histogram,
  Coin,
  DataBoard,
  PieChart,
  Warning,
  Message,
  Upload,
  Download
} from '@element-plus/icons-vue'

const deviceStore = useDeviceStore()
const authStore = useAuthStore()
const { currentDevice } = storeToRefs(deviceStore)

// 检查用户权限
const userRole = computed(() => authStore.getUserRole)
const hasPermission = computed(() => {
  return userRole.value === 'LV1' || userRole.value === 'LV2'
})

// 数据项列表
const dataItems = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框控制
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const submitting = ref(false)

// 删除对话框
const deleteDialogVisible = ref(false)
const currentItem = ref(null)
const deleting = ref(false)

// 表单数据
const form = reactive({
  name: '',
  unit: '',
  display_mode: 'number',
  icon: 'Monitor',
  color: '#409EFF',
  mapping_name: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入数据项名称', trigger: 'blur' },
    { max: 50, message: '名称长度不能超过50个字符', trigger: 'blur' }
  ],
  mapping_name: [
    { required: true, message: '请输入映射名称', trigger: 'blur' },
    { max: 100, message: '映射名长度不能超过100个字符', trigger: 'blur' }
  ],
  display_mode: [
    { required: true, message: '请选择显示方式', trigger: 'change' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ]
}

// 可用图标列表
const availableIcons = [
  { name: 'Monitor' },
  { name: 'Connection' },
  { name: 'DataLine' },
  { name: 'Setting' },
  { name: 'Timer' },
  { name: 'Odometer' },
  { name: 'TrendCharts' },
  { name: 'Box' },
  { name: 'Loading' },
  { name: 'Histogram' },
  { name: 'Coin' },
  { name: 'DataBoard' },
  { name: 'PieChart' },
  { name: 'Warning' },
  { name: 'Message' }
]

// 打开新增对话框
const openAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row) => {
  isEdit.value = true
  resetForm()
  Object.keys(form).forEach(key => {
    if (key in row) {
      form[key] = row[key]
    }
  })
  form.id = row.id // 保存ID用于更新
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  form.name = ''
  form.unit = ''
  form.display_mode = 'number'
  form.icon = 'Monitor'
  form.color = '#409EFF'
  form.mapping_name = ''
  delete form.id
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    if (!currentDevice.value) {
      ElMessage.warning('请先选择设备')
      return
    }
    
    submitting.value = true
    try {
      const deviceId = currentDevice.value.id
      const deviceName = currentDevice.value.equipment_name
      
      // 构建数据项对象
      const dataItem = {
        name: form.name,
        unit: form.unit,
        display_mode: form.display_mode,
        icon: form.icon,
        color: form.color,
        mapping_name: form.mapping_name
      }
      
      // 准备发送到API的数据
      const apiData = {
        device_id: deviceId,
        device_name: deviceName,
        ab1: JSON.stringify(isEdit.value ? 
          // 更新时，保留其他数据项，只更新当前编辑的
          dataItems.value.map(item => 
            item.id === form.id ? { ...item, ...dataItem } : item
          ) : 
          // 新增时，添加到数组末尾
          [...dataItems.value, { ...dataItem, id: Date.now() }]
        )
      }
      
      const token = localStorage.getItem('token')
      const response = await fetch('/api/low-code-data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(apiData),
        credentials: 'include'
      })
      
      const result = await response.json()
      
      if (result.code === 200) {
        ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
        dialogVisible.value = false
        fetchDataItems() // 刷新数据
      } else {
        ElMessage.error(result.message || '操作失败')
      }
    } catch (error) {
      console.error('提交数据项失败:', error)
      ElMessage.error('操作失败，请重试')
    } finally {
      submitting.value = false
    }
  })
}

// 确认删除
const confirmDelete = (row) => {
  currentItem.value = row
  deleteDialogVisible.value = true
}

// 删除数据项
const deleteItem = async () => {
  if (!currentDevice.value || !currentItem.value) return
  
  deleting.value = true
  try {
    const deviceId = currentDevice.value.id
    const deviceName = currentDevice.value.equipment_name
    
    // 过滤掉要删除的数据项
    const updatedItems = dataItems.value.filter(item => item.id !== currentItem.value.id)
    
    // 准备发送到API的数据
    const apiData = {
      device_id: deviceId,
      device_name: deviceName,
      ab1: JSON.stringify(updatedItems)
    }
    
    const token = localStorage.getItem('token')
    const response = await fetch('/api/low-code-data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(apiData),
      credentials: 'include'
    })
    
    const result = await response.json()
    
    if (result.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      fetchDataItems() // 刷新数据
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    console.error('删除数据项失败:', error)
    ElMessage.error('删除失败，请重试')
  } finally {
    deleting.value = false
    deleteDialogVisible.value = false
  }
}

// 获取数据项列表
const fetchDataItems = async () => {
  if (!currentDevice.value) return
  
  loading.value = true
  try {
    const deviceId = currentDevice.value.id
    const token = localStorage.getItem('token')
    
    console.log('正在获取设备数据项，设备ID:', deviceId)
    
    const response = await fetch(`/api/low-code-data/device/${deviceId}`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      },
      credentials: 'include'
    })
    
    const result = await response.json()
    console.log('API返回数据:', result)
    
    if (result.code === 200 && result.data) {
      try {
        console.log('开始解析数据项，API返回数据结构:', typeof result.data)
        
        // 处理数组形式的返回数据
        if (Array.isArray(result.data)) {
          // 遍历数组查找包含ab1字段的对象
          for (const item of result.data) {
            if (item && item.ab1) {
              try {
                const parsedData = JSON.parse(item.ab1)
                if (Array.isArray(parsedData)) {
                  dataItems.value = parsedData
                  break
                }
              } catch (parseError) {
                console.error('解析ab1字段失败:', parseError)
              }
            }
          }
        } 
        // 处理对象形式的返回数据
        else if (result.data.ab1) {
          try {
            const parsedData = JSON.parse(result.data.ab1)
            if (Array.isArray(parsedData)) {
              dataItems.value = parsedData
            } else if (typeof parsedData === 'object') {
              dataItems.value = Object.values(parsedData)
            }
          } catch (parseError) {
            console.error('解析ab1字段失败:', parseError)
          }
        }
        
        // 确保dataItems是数组类型
        if (!Array.isArray(dataItems.value)) {
          dataItems.value = []
        }
        
        total.value = dataItems.value.length
        console.log('设置数据项总数:', total.value)
      } catch (e) {
        console.error('处理数据失败:', e)
        dataItems.value = []
        total.value = 0
      }
    } else {
      console.warn('API返回错误或无数据:', result)
      dataItems.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取数据项失败:', error)
    ElMessage.error('获取数据项失败')
    dataItems.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 监听设备变化，重新获取数据
watch(() => currentDevice.value, (newDevice) => {
  if (newDevice) {
    fetchDataItems()
  } else {
    dataItems.value = []
    total.value = 0
  }
}, { immediate: true })

// 初始化
onMounted(() => {
  if (currentDevice.value) {
    fetchDataItems()
  }
})

// 计算分页后的数据项
const paginatedDataItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return dataItems.value.slice(startIndex, endIndex)
})
// 格式化数据值
const formatValue = (value, displayMode) => {
  if (value === undefined || value === null || value === '') {
    return '无数据'
  }
  
  if (displayMode === 'number') {
    const numValue = parseFloat(value)
    return isNaN(numValue) ? '无效数值' : numValue.toFixed(2)
  } else if (displayMode === 'status') {
    return value.toString()
  } else {
    return value
  }
}

// 测试数据项
const testDataItem = async (row) => {
  if (!currentDevice.value) {
    ElMessage.warning('请先选择设备')
    return
  }

  // 设置测试状态
  row.testing = true
  try {
    const deviceNumber = currentDevice.value.equipment_name.match(/设备(\d+)/)?.[1]
    if (!deviceNumber) {
      throw new Error('无效的设备名称')
    }

    const token = localStorage.getItem('token')
    const response = await fetch(`/api/oil/data/${deviceNumber}?page=1&page_size=1`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      },
      credentials: 'include'
    })

    if (!response.ok) {
      throw new Error('获取设备数据失败')
    }

    const result = await response.json()
    if (result.code === 200) {
      let data
      if (result.data?.list?.length > 0) {
        data = result.data.list[0]
      } else if (Array.isArray(result.data) && result.data.length > 0) {
        data = result.data[0]
      }

      if (data) {
        // 更新测试值
        const rawValue = data[row.mapping_name]
        row.testValue = rawValue ? formatValue(rawValue, row.display_mode) : '无数据'
        ElMessage.success('测试成功')
      } else {
        row.testValue = '无数据'
        ElMessage.warning('未获取到数据')
      }
    } else {
      throw new Error(result.message || '获取数据失败')
    }
  } catch (error) {
    console.error('测试数据项失败:', error)
    ElMessage.error(error.message || '测试失败')
    row.testValue = '测试失败'
  } finally {
    row.testing = false
  }
}
</script>

<style scoped>
.data-item-manager {
  padding: 20px;
}

.header-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.color-preview {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>